let _Vue = null
export default class VueRouter {
  static install(Vue) {
    //判断是否挂载路由函数， 挂载router函数到vue实例的原型上
    if (VueRouter.install.installed) return;
    VueRouter.install.installed = true
    _Vue = Vue
    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          //vue实例上才会注册路由 组件不会有这个属性
          this.prototype.router = this.$options.router
        }
      }
    })
  }
  constructor(options) {
    //保存路由配置 初始化routemap 初始化路由  初始化当前路由路径 形成响应式数据
    this.options = options
    this.routermap = {}
    this.data = _Vue.observable({
      current: "/"
    })
    this.init()
  }
  init() {
    this.createRouteMap()
    this.initComponent(_Vue)
    this.initEvent()
  }
  createRouteMap() {
    //极简路由 没考虑子路由和name 
    this.options.routers.forEach(route => {
      this.routermap[route.path] = route.component
    })
  }
  initComponent(Vue) {
    //生成routerlink 组件 和 routerview  组件 
    vue.component('router-link', {
      props: {
        to: string
      },
      render(h) {
        return h(a, {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickhander
          }
        }, [this.$slots.default])
      },
      methods: {
        clickhander() {
          history.pushState({}, "", this.to)
          this.$router.data.current = this.to
          e.preventDefault()
        }
      }
    })
    let self = this
    vue.component('router-view', {
      render(h) {
        const cm = self.routeMap[self.data.current]
        return h(cm)
      }
    })
  }
  initEvent() {
    // mode: 'history' 'hash',
    if (this.options.mode == 'hash') {
      window.addEventListener('hashchange', () => {
        this.data.current = location.hash.substr(1)
      })
    } else {
      window.addEventListener('popstate', () => {
        this.data.current = location.pathname
      })
    }
  }
}